<?php

/**
 * Class Common_network
 */
class Common_network extends CI_Model
{
    /**
     * Common_network constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $session= $this->session->userdata('sessioninfo');
        $this->userId = $session['userId'];
    }

    /** 判断IP地址格式是否正确
     *
     * @param $ip IP地址
     * @return int 1=是，0=否
     */
    public function isOk_ip($ip)
    {
        if (preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1 -9]?\d))))$/', $ip)) {
            return 1;
        } else {
            return 0;
        }
    }

    /** 判断掩码格式是否正确
     *
     * @param $mask 掩码
     * @return int hp判断IP地址格式是否正确
     */
    public function isOk_mask($mask)
    {
        if (!is_numeric($mask)) return 0;
        if ($mask > 32) return 0;
        if ($mask < 8) return 0;
        return 1;
    }


    /** 地址/掩码 分析
     *
     * @param $ip_str 输入的IP地址和掩码
     * @return array  结果看后面演示
     */
    public function ip_parse($ip_str)
    {
        $mark_len = 32;
        if (strpos($ip_str, "/") > 0) {
            list($ip_str, $mark_len) = explode("/", $ip_str);
        }
        $ip = ip2long($ip_str);
        $mark = 0xFFFFFFFF << (32 - $mark_len) & 0xFFFFFFFF;
        $ip_start = $ip & $mark;
        $ip_end = $ip | (~$mark) & 0xFFFFFFFF;
        return array($ip, $mark, $ip_start, $ip_end);
    }
    //演示：
    //list($ip, $mark, $ip_start, $ip_end) = ip_parse("192.168.1.12/24");
    //echo "IP地址 : ", long2ip($ip), "\n";
    //echo "子网掩码: ", long2ip($mark), "\n";
    //echo "IP段开始: ", long2ip($ip_start), "\n";
    //echo "IP段结束: ", long2ip($ip_end), "\n";


    public function isIPRang($ipaddress)
    {
        if ($ipaddress == "") return array();
        self::checkPreg('/[0-9,-]+/', $ipaddress, "IP地址范围不正确！");
        $list = explode(',', $ipaddress);
        $result = array();
        foreach ($list as $item) {
            self::checkPreg('/([0-9]+)(-[0-9]+)|([0-9]+)/', $item, "IP地址范围不正确！");
            $itemlist = explode('-', $item);
            if (sizeof($itemlist) == 1) {
                if ($itemlist[0] > 255) self::_JSONRESULT("IP地址范围不正确！");
                if ($itemlist[0] == 0) self::_JSONRESULT("IP地址范围不正确！");
                $result[$itemlist[0]] = $itemlist[0];
            } else {
                if ($itemlist[0] > 255) self::_JSONRESULT("IP地址范围不正确！");
                if ($itemlist[0] == 0) self::_JSONRESULT("IP地址范围不正确！");
                if ($itemlist[1] > 255) self::_JSONRESULT("IP地址范围不正确！");
                if ($itemlist[1] == 0) self::_JSONRESULT("IP地址范围不正确！");
                if ($itemlist[0] > $itemlist[1]) self::_JSONRESULT("IP地址范围不正确！");
                for ($i = $itemlist[0]; $i <= $itemlist[1]; $i++) $result[$i] = $i;
            }
        }
        return $result;
    }

    private function checkPreg($pattern, $data, $errorMsg)
    {
        $list = array();
        preg_match($pattern, $data, $list);
        if (sizeof($list) == 0) {
            self::_JSONRESULT($errorMsg);
        }
        if ($list[0] <> $data) {
            self::_JSONRESULT($errorMsg);
        }
    }

    /** 根据IP和地址类型，产生对应的IP表数据
     *
     * @param $network  对应的网段表的记录
     * @param $typeArr 地址类型二维数组
     */
    public function ipCreate($network, $typeArr)
    {
        $typelist = array();
        $types = array();
        foreach($typeArr as $item){
            $typelist[$item['msg1']] = self::isIPRang($network[$item['msg1']]);
            $types[$item['msg1']] = $item['name'];
        }
        $this->load->model("public/Common_tools", "tools");
        $ipaddress = $network["NETWORK"] . '/' . $network['MASK'];
        $ipdata = self::ip_parse($ipaddress);
        $param = array('USEFULL');
        $inserts = array();
        for ($i = $ipdata[2] + 1; $i <= $ipdata[3]; $i++) {
            $insert = array();
            $insert['ID_NETWORK'] = $network['ID'];
            $insert['IP'] = long2ip($i);
            foreach ($param as $item) {
                $insert[$item] = $network[$item];
            }
            $iplist = explode('.', $insert['IP']);
            $insert['TYPE'] = '其他地址';
            foreach ($typelist as $key=>$item) {
                if (isset($typelist[$key][$iplist[3]])) $insert['TYPE'] = $types[$key];
            }
            $insert['STATUS'] = '未登录';
            $insert = $this->tools->_dbaddtion($insert);
            $inserts[] = $insert;
        }
        $this->db->insert_batch('nd_ip', $inserts);
        $update = array();
        $update['STATUS'] = 'IP已展开';
        $update['modifydatetime'] = Date('Y-m-d H:i:s');
        $update['modifyuser'] = $this->userId;
        $this->db->where('ID',$network['ID']);
        $this->db->update('nd_network',$update);
        return true;
    }

    /** AJAX 返回 跟踪信息,直接返回了
     * @param string $message
     * @param bool $ok
     */
    protected function _JSONRESULT($message = '错误信息', $ok = false)
    {
        $result = array();
        $result["success"] = $ok;
        $result["msg"] = print_r($message, true);
        $result["obj"] = "";
        echo json_encode($result);
        exit;
    }

    public function checkAddAcl($config){
        $where = "(SRC_NETWORK = '".$config['NETWORK']."' OR DES_NETWORK='".$config['NETWORK']."') AND (IS_DISABLED = 0)";
        $this->db->where($where);
        $data = $this->db->get("nd_acl")->result_array();
        if (sizeof($data) == 0){
            $dd = $this->db->query("SELECT DISTINCT SRC_NETWORK,SRC_NAME,SRC_MASK FROM nd_acl WHERE IS_DISABLED=0")->result_array();
            $inserts = array();
            foreach($dd as $item){
                $insert = array();
                $insert['SRC_NAME'] = $config['NAME'];
                $insert['SRC_NETWORK'] = $config['NETWORK'];
                $insert['SRC_MASK'] = $config['MASK'];
                $insert['DES_NAME'] = $item['SRC_NAME'];
                $insert['DES_NETWORK'] = $item['SRC_NETWORK'];
                $insert['DES_MASK'] = $item['SRC_MASK'];
                $insert['STATUS'] = '×';
                $insert['IS_DISABLED'] = 0;
                $insert['createdatetime'] = Date('Y-m-d H:i:s');
                $insert['createuser'] = $this->userId;
                $inserts[] = $insert;
            }
            foreach($dd as $item){
                $insert = array();
                $insert['DES_NAME'] = $config['NAME'];
                $insert['DES_NETWORK'] = $config['NETWORK'];
                $insert['DES_MASK'] = $config['MASK'];
                $insert['SRC_NAME'] = $item['SRC_NAME'];
                $insert['SRC_NETWORK'] = $item['SRC_NETWORK'];
                $insert['SRC_MASK'] = $item['SRC_MASK'];
                $insert['STATUS'] = '×';
                $insert['IS_DISABLED'] = 0;
                $insert['createdatetime'] = Date('Y-m-d H:i:s');
                $insert['createuser'] = $this->userId;
                $inserts[] = $insert;
            }
            $this->db->insert_batch("nd_acl",$inserts);
            $this->_JSONRESULT("有关于网段".$config['NETWORK']."的ACL数据新增加，请进行配置!",true);
        }
    }


    public function batchAclupdate($params){
        $ids = implode(',',$params['ID']);
        $sql = "SELECT ID FROM nd_acl na,(SELECT SRC_NETWORK,SRC_MASK,DES_NETWORK,DES_MASK FROM nd_acl WHERE ID in ($ids)) t
                 WHERE na.SRC_NETWORK=t.DES_NETWORK AND na.SRC_MASK=t.DES_MASK AND na.DES_NETWORK=t.SRC_NETWORK AND na.DES_MASK=t.SRC_MASK AND na.IS_DISABLED=0";
        $data = $this->db->query($sql)->result_array();
        $ids = $params['ID'];
        foreach ($data as $item) $ids[]=$item['ID'];
        $this->db->where_in('ID',$ids);
        $update = array();
        foreach ($params as $key => $item){
            if ($key == 'ID') continue;
            if ($item == "") continue;
            $update[$key] = $item;
        }
        $update['CFG_TIME'] = Date('Y-m-d H:i:s');
        $update['modifydatetime'] = Date('Y-m-d H:i:s');
        $update['modifyuser'] =  $this->userId;
        $this->db->update("nd_acl",$update);
        self::_JSONRESULT("批量更新成功！",true);
    }
}
